package com.jy.rhin.config.infra;

import lombok.Data;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author WeiQ
 * @date 2022/7/20 16:14
 * rabbitMQ 相关配置
 */
@Configuration("infraRhinRabbitConfig")
@EnableConfigurationProperties({RhinRabbitConfig.RhinRabbitConfigurationProperties.class})
public class RhinRabbitConfig {

    @Resource
    RhinRabbitConfigurationProperties rhinRabbitConfigurationProperties;



    /**
     * 声明基础服务的MQ消息交换机
     *
     * @param exchange
     * @return
     */
    @Bean("publishMessageExchange")
    public TopicExchange delayedExchange(@Value("${rhin.amqp.exchange}") String exchange) {
        return new TopicExchange(exchange, true, false);
    }

    /**
     * 声明基础服务-事件总线监听MQ消息的queue
     *
     * @return
     */
    @Bean("notificationInfraQueue")
    public Queue notificationInfraQueue() {
        return new Queue(rhinRabbitConfigurationProperties.getNotificationQueue());
    }

    /**
     * 绑定路由：
     * 1、 共享文档提交/注册事件的消息，发送到${documentProviderAndRegisterRoutingKey}key，需要路由到事件总线监听的队列${notificationQueue}
     * 2、 后续其他业务(EMPI/医疗资源/术语系统等)发送的事件消息，需要添加key，将消息路由到事件总线监听的队列(后续通过rabbitMQ控制台添加，不再修改代码)
     *
     * @param notificationQueue
     * @param publishMessageExchange
     * @return
     */
    @Bean("notificationBinding")
    public Binding binding(Queue notificationQueue, TopicExchange publishMessageExchange) {
        return BindingBuilder
                .bind(notificationQueue)
                .to(publishMessageExchange)
                .with(rhinRabbitConfigurationProperties.getDocumentProviderAndRegisterRoutingKey())
                ;
    }

    @ConfigurationProperties(prefix = "rhin.amqp")
    @Data
    public static class RhinRabbitConfigurationProperties {
        /**
         * 基础服务发布MQ消息的目标交换机
         */
        private String exchange;
        /**
         * 发布【通知订阅者】消息的路由key
         */
        private String publishMessageRoutingKey;
        /**
         * 发布【文档提交注册事件】消息的路由key
         */
        private String documentProviderAndRegisterRoutingKey;
        /**
         * 事件总线(基础服务)监听业务事件的queue
         */
        private String notificationQueue;
    }

}
